import Flutter
import UIKit
import BDASignalSDK

public class KbBytedanceAttributionPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "kb_bytedance_attribution", binaryMessenger: registrar.messenger())
    let instance = KbBytedanceAttributionPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "getPlatformVersion":
      result("iOS " + UIDevice.current.systemVersion)
    case "registerWithOptionalData":
        let userUniqueId = call.arguments as? String
        BDASignalManager.register(withOptionalData: [
            kBDADSignalSDKUserUniqueId : userUniqueId ?? ""
        ])
        result(nil)
    case "eventRegister":
        BDASignalManager.trackEssentialEvent(withName: kBDADSignalSDKEventRegister, params: call.arguments as? [AnyHashable : Any])
        result(nil)
    case "eventStayTime":
        BDASignalManager.trackEssentialEvent(withName: kBDADSignalSDKEventStayTime, params: call.arguments as? [AnyHashable : Any])
        result(nil)
    case "eventPurchase":
        BDASignalManager.trackEssentialEvent(withName: kBDADSignalSDKEventPurchase, params: call.arguments as? [AnyHashable : Any])
        result(nil)
    case "eventGameAddiction":
        BDASignalManager.trackEssentialEvent(withName: kBDADSignalSDKEventGameAddiction, params: call.arguments as? [AnyHashable : Any])
        result(nil)
    case "eventCustom":
        let eventName = (call.arguments as? Dictionary<String, Any>)!["eventName"] as! String
        let params = (call.arguments as? Dictionary<String, Any>)!["params"] as! [AnyHashable : Any]
        BDASignalManager.trackEssentialEvent(withName: eventName, params: call.arguments as? [AnyHashable : Any])
        result(nil)
    case "enableIdfa":
        let enable = call.arguments as! Bool
        BDASignalManager.enableIdfa(enable)
        result(nil)
    case "getClickId":
        let clickId = BDASignalManager.getClickId()
        result(clickId)
    default:
      result(FlutterMethodNotImplemented)
    }
  }
}
